package cheme.Interpreter.AST.SymbolTable;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cheme.Interpreter.AST.Interfaces.IAstString;
import cheme.Interpreter.AST.Interfaces.IAstVariable;
import cheme.Interpreter.AST.Interfaces.IObserver;
import cheme.Interpreter.AST.Interfaces.ISubject;
import cheme.Interpreter.AST.Interfaces.SubjectCore;



public class SymbolTable implements ISubject, IObserver
{
	Map<String, IAstVariable> hash = new HashMap<String, IAstVariable>();
	
	private SubjectCore subjectCore = new SubjectCore(this);
	
	public void add(IAstVariable var)
	{
		if(null != var)
		{
			String key = var.getIdentifier().toString(); 
			if(!hash.containsKey(key))
			{
				hash.put(key, var);
				var.attach(this);
			}
		}
	}
	
	public void remove(IAstVariable var)
	{
		if(null != var)
		{
			remove(var.getIdentifier().toString());
		}
	}
	
	public void remove(String key)
	{
		if(!hash.containsKey(key))
		{
			get(key).detach(this);
			hash.remove(key);
		}
	}
	
	public IAstVariable get(String identifier)
	{
		return hash.get(identifier);
	}
	
	public IAstVariable get(IAstString identifier)
	{
		return hash.get(identifier.toString());
	}
	
	public void notify(ISubject s)
	{
		/*
		 * Echo cahnges to varaible to all listeners.
		 */
		notifyObservers();
	}
	
	public void attach(IObserver o)
	{
		subjectCore.attach(o);
	}

	public void detach(IObserver o)
	{
		subjectCore.detach(o);
	}

	public void notifyObservers()
	{
		subjectCore.notifyObservers();
	}
	
	public Iterator<IAstVariable> iterator()
	{
		return hash.values().iterator();
	}
}
